package com.objecteffects.template.service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import com.google.inject.Inject;
import com.google.inject.persist.Transactional;

import com.objecteffects.template.persist.api.IGenericDao;

/**
 * Doesn't work. Transactions are messed up.
 *
 * @author Rusty Wright
 */
abstract class AbstractEntityService<T extends Serializable> {
    private final IGenericDao<T> dao;

    /** */
    @Inject
    AbstractEntityService(final IGenericDao<T> _dao) {
        this.dao = _dao;
    }

    @Transactional
    public void saveAll(final Collection<T> input) {
        for (final T each : input) {
            if (each != null) {
                this.dao.save(each);
            }
        }
    }

    @Transactional
    public void save(final T entity) {
        this.dao.save(entity);
    }

    @Transactional
    public T findById(final Long id) {
        return this.dao.findOne(id);
    }

    @Transactional
    public List<T> findAll() {
        final List<T> result = this.dao.findAll();

        return result;
    }

    @Transactional
    public void deleteById(final Long entityId) {
        this.dao.deleteById(entityId);
    }

    @Transactional
    public T update(final T entity) {
        return this.dao.update(entity);
    }

    @Transactional
    public void deleteAll() {
        final List<T> result = this.dao.findAll();

        for (final T entity : result) {
            this.dao.delete(entity); // .deleteById(entity.getId());
        }
    }

    /**
     * @return the dao
     */
    public IGenericDao<T> getDao() {
        return this.dao;
    }
}
